# -*- coding: utf-8 -*-
# Copyright Š 2010 alexliyu
#
# This file is part of cntop-news.
#
# cntop-news is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cntop-news is base on Top-news-buzz ,
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cntop-news.  If not, see <http://www.gnu.org/licenses/>.

import os
import logging
from google.appengine.api import memcache

from topnewsbuzz.controller import MainPage
from topnewsbuzz.config import ConfigValue, MetricConfigEntry, Config
from topnewsbuzz.feed import Feed
from topnewsbuzz.lib import feedstest
from topnewsbuzz.metrics import MetricHelper

class AdminPage(MainPage):

    def service(self):
        memcache.flush_all()

        self.template_url = '../admin/config.html'


class ConfigAdminPage(AdminPage):

    def service(self):
        super(ConfigAdminPage, self).service()

        config_path = os.path.join(os.path.dirname(__file__), '../admin/main.html')

        self.template_values.update({'config' : Config,
                                     'config_path' : config_path})

    def post(self):
        for config_key in self.request.params:
            config = ConfigValue.get_or_insert(key_name = config_key)
            config.value = self.request.params[config_key]
            config.put()

        self.redirect(self.request.url)

class FeedAdminPage(AdminPage):

    def service(self):
        super(FeedAdminPage, self).service()

        config_path = os.path.join(os.path.dirname(__file__), '../admin/feeds.html')

        self.template_values.update({'feeds' : Config.get_feeds(),
                                     'config_path' : config_path})

    def post(self):
        feed_urls_to_delete = self.request.get_all('feed_url_old')
        feed_urls = self.request.get_all('feed_url')
        feed_boost = self.request.get_all('feed_boost')
        feed_target = self.request.get_all('feed_target')
        for feed_index in range(len(feed_urls)):
            url = feed_urls[feed_index]
            if url != '':
                feed = Feed.get_or_insert(url, url = url)
                try:
                    boost = feed_boost[feed_index]
                    feed.boost = float(boost)
                    target=feed_target[feed_index]
                    feed.target=str(target)
                except ValueError:
                    feed.boost = 1.0
                    feed.target='#body'
                feed.put()
                if url in feed_urls_to_delete:
                    feed_urls_to_delete.remove(url)

        for url in feed_urls_to_delete:
            feed = Feed.get_by_key_name(url)
            feed.delete()

        self.redirect(self.request.url)

class MetricAdminPage(AdminPage):

    def service(self):
        super(MetricAdminPage, self).service()

        metrics = MetricHelper.load_metrics()

        config_path = os.path.join(os.path.dirname(__file__), '../admin/metrics.html')

        self.template_values.update({'metrics' : metrics,
                                     'config_path' : config_path,
                                     'MetricConfigEntry' : MetricConfigEntry })


    def post(self):
        for metric_config_key in self.request.params:
            MetricConfigEntry.store(metric_config_key, self.request.params[metric_config_key])

        self.redirect(self.request.url)

class FeedtestAdminPage(AdminPage):

    def service(self):
        super(FeedtestAdminPage, self).service()

        config_path = os.path.join(os.path.dirname(__file__), '../admin/feedstest.html')
        self.template_values.update({'config_path' : config_path})

    def post(self):
        feed_urls = self.request.get_all('feed_url')
        feed_target = self.request.get_all('feed_target')
        feedstest.getresult(feed_urls, feed_target)
        if len(feedstest.theresult)!=None:
            print '采集已完成，共采集数为：'
            print len(feedstest.theresult)
            tempstr=feedstest.theresult[1]
            tempss=type(tempstr)
            logging.info(tempstr)
            print tempstr[0].encode('utf-8')
        else:
            print 'Sorry,none of the result'
        feedstest.theresult=[]

        #self.redirect(self.request.url)
